<template>
  <div class="mt-1">
    <van-form>
      <van-field
        label="关联单号"
        placeholder="点击此处获取关联单号"
        :value="orderPur"
        :label-width="labelWidth"
        is-link
        readonly
        @click="getOrderNum"
      ></van-field>
      <!-- 工厂 -->
      <!-- <van-field
        :value="orderNum"
        label="发货工厂"
        :label-width="labelWidth"
        readonly
        placeholder="请点击关联单号"
      >
      </van-field> -->
      <div class="first">
        <van-field
          readonly
          clickable
          arrow-direction="down"
          is-link
          label="目视检查"
          :label-width="labelWidth"
          :value="value_ms"
          @click="showPicker_ms = true"
        />
        <van-popup v-model="showPicker_ms" round position="bottom">
          <van-picker
            show-toolbar
            :columns="ChooseStatue"
            @cancel="showPicker_ms = false"
            @confirm="makeSure"
          />
        </van-popup>
        <van-field
          readonly
          clickable
          arrow-direction="down"
          is-link
          label="提前带养"
          :label-width="labelWidth"
          :value="value_tqdy"
          @click="showPicker_tqdy = true"
        />
        <van-popup v-model="showPicker_tqdy" round position="bottom">
          <van-picker
            show-toolbar
            :columns="ChooseStatue"
            @cancel="showPicker_tqdy = false"
            @confirm="makeSureTQ"
          />
        </van-popup>
      </div>
      <div class="first">
        <van-field
          readonly
          clickable
          arrow-direction="down"
          is-link
          label="COA"
          :label-width="labelWidth"
          :value="value_coa"
          @click="showPicker_coa = true"
        />
        <van-popup v-model="showPicker_coa" round position="bottom">
          <van-picker
            show-toolbar
            :columns="ChooseStatue"
            @cancel="showPicker_coa = false"
            @confirm="makeSureCOA"
          />
        </van-popup>
        <van-field
          readonly
          clickable
          arrow-direction="down"
          is-link
          label="散装"
          :label-width="labelWidth"
          :value="value_sz"
          @click="showPicker_sz = true"
        />
        <van-popup v-model="showPicker_sz" round position="bottom">
          <van-picker
            show-toolbar
            :columns="ChooseStatue"
            @cancel="showPicker_sz = false"
            @confirm="makeSureSZ"
          />
        </van-popup>
      </div>
      <!-- 拍码 -->
      <van-field
        v-model="code"
        clearable
        label="拍码"
        :label-width="labelWidth"
        placeholder="请扫描拍码"
        ref="code"
        @focus="focus"
      />
      <ag-grid-vue
        style="width: 100%; height: 50vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row type="flex" gutter="30" justify="center">
        <van-col span="9">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <van-col span="9"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>

      <!-- <p-o-com-dialog
        :statu="show"
        :DX="DX"
        @confirmButton="confirmButton"
        @cancelButton="cancelButton"
      ></p-o-com-dialog> -->
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-data-z-s :ShowDataA="ShowData" @get-val="Sure" />
      </van-popup>
      <van-popup
        v-model="OrderNumVisible"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <order-num-po @close="close" @get_date="get_date" />
      </van-popup>
    </van-form>
    <!-- 展示数量不符的物料名称 -->
    <van-dialog v-model="ifShowNoFit" title="提示">
      <div v-for="(item, index) in noFitWuliao" :key="index">
        <div class="tip">{{ item }}------超出库存</div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import {
  InformationSubmit,
  PostOrder,
  PostDetail,
} from "../../assets/api/post";

import { toast, parseQRCode } from "../../untils/commion";
import ShowDataZS from "../../components/ShowData.vue";
import { AgGrid } from "../../minx/AgGrid";
import orderNumPo from "./OrderNumPO.vue";

export default {
  components: { AgGridVue, ShowDataZS, orderNumPo },
  mixins: [AgGrid],
  data() {
    return {
      // 控制关联单号组件是否显示
      // ifShowOrderNum: false,
      ifShowNoFit: false,
      OrderNumVisible: false,
      labelWidth: "7em",
      titles: new Map().set(2, "PO收货"),
      showPicker_ms: false,
      showPicker_tqdy: false,
      showPicker_coa: false,
      showPicker_sz: false,
      type: null,
      show: false,
      location: "",
      ShowStatue: false,
      value_ms: "",
      value_tqdy: "",
      value_coa: "",
      value_sz: "",
      ms: "",
      tqdy: "",
      coa: "",
      sz: "",
      code: "",
      orderNum: "",
      orderPur: "",
      columnDefs: [
        { headerName: "物料", field: "materialCode", flex: 1.5 },
        { headerName: "拍号", field: "palletNo", flex: 2 },
        { headerName: "数量", field: "quantity", flex: 1.5 },
      ],
      ChooseStatue: ["是", "否", "空"],
      rowData: [],
      submit: {},
      detailData: [],
      sure: "",
      zt: true,
      info: [],
      DX: [],
      ShowData: {},
      Res: {},
      stoDate: [],
      newMaterial: [], //存放物料号
      startDate: "", //开始日期
      endDate: "", //结束日期
      keyword: "", //搜索关键字
      newArry: [],
      item: "", //存放子项编号
      // 用于验证的数据
      newDetails: [], //存放最新的明细数据
      copyTable: [], //复制表格数据
      allName: [], //存放所有的物料号
      noFitWuliao: [], //存放超出数量标准的物料名称
    };
  },
  watch: {
    code(newValue) {
      if (this.orderNum) {
        if (newValue.length > 9) {
          let res = parseQRCode(newValue);
          this.Res = JSON.parse(JSON.stringify(res));
          if (res) {
            // 校验生产商，供应商，日期是否为空
            if (res.gsVendor == null || res.gsVendor == "") {
              this.$toast("拍码生产商为空");
              this.code = "";
              return;
            }
            if (res.commerialVendor == null || res.commerialVendor == "") {
              this.$toast("拍码供应商为空");
              this.code = "";
              return;
            }
            if (res.prodDate == null || res.prodDate == "") {
              this.$toast("拍码生产日期为空");
              this.code = "";
              return;
            }
            // PO校验
            if (this.newMaterial.indexOf(res.materialCode) == -1) {
              toast("订单中不存在该物料");
              this.code = "";
              return;
            }

            if (!this.rowData.find((it) => it.palletNo == res.palletNo)) {
              this.ShowData = JSON.parse(JSON.stringify(res));
              // 改变日期格式
              let SC = "20" + this.ShowData.prodDate;
              let YX = "20" + this.ShowData.BBD;
              this.ShowData.prodDate =
                SC.substring(0, 4) +
                "-" +
                SC.substring(4, 6) +
                "-" +
                SC.substring(6, 8);
              this.ShowData.BBD =
                YX.substring(0, 4) +
                "-" +
                YX.substring(4, 6) +
                "-" +
                YX.substring(6, 8);
              this.ShowStatue = true;
              if (this.ShowData) {
                this.rowData.push(res);

                let restwo = {
                  materialCode: res.materialCode,
                  quantity: res.quantity,
                };
                this.allName = [];
                if (this.copyTable[0] == null) {
                  this.copyTable.push(restwo);
                } else {
                  this.copyTable.forEach((item) => {
                    if (restwo.materialCode == item.materialCode) {
                      item.quantity += restwo.quantity;
                    }
                    //存放所有的物料号
                    this.allName.push(item.materialCode);
                  });
                  // 判断如果没有该物料号就添加
                  if (this.allName.indexOf(restwo.materialCode) == -1) {
                    this.copyTable.push(restwo);
                  }
                }
              }
              res = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
      } else {
        toast("请先选择关联单号");
      }
      this.code = "";
    },
  },
  methods: {
    get_date(val) {
      this.stoDate = val;
      this.newMaterial = [];
      // 调用该函数获取去重后的比较数据
      this.getNoRepeat();
    },
    getNoRepeat() {
      this.stoDate.forEach((val) => {
        this.newMaterial.push(val.material);
      });
    },

    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    close(startDate, endDate, keyword) {
      this.startDate = startDate; //获取开始日期
      this.endDate = endDate; //获取结束日期
      this.keyword = keyword; //获取搜索关键字
      this.orderNum = this.$store.state.numpo;
      this.orderPur = this.$store.state.purno;
      this.OrderNumVisible = false;
    },
    makeSure(value_ms) {
      switch (value_ms) {
        case "是":
          this.ms = "A";
          break;
        case "否":
          this.ms = "R";
          break;
        case "空":
          this.ms = "";
          break;
      }
      this.value_ms = value_ms;
      this.showPicker_ms = false;
    },
    makeSureTQ(value_tqdy) {
      switch (value_tqdy) {
        case "是":
          this.tqdy = "A";
          break;
        case "否":
          this.tqdy = "R";
          break;
        case "空":
          this.tqdy = "";
          break;
      }
      this.value_tqdy = value_tqdy;
      this.showPicker_tqdy = false;
    },
    makeSureCOA(value_coa) {
      switch (value_coa) {
        case "是":
          this.coa = "A";
          break;
        case "否":
          this.coa = "R";
          break;
        case "空":
          this.coa = "";
          break;
      }
      this.value_coa = value_coa;
      this.showPicker_coa = false;
    },
    makeSureSZ(value_sz) {
      switch (value_sz) {
        case "是":
          this.sz = 1;
          break;
        case "否":
          this.sz = 0;
          break;
        case "空":
          this.sz = "";
          break;
      }
      this.value_sz = value_sz;
      this.showPicker_sz = false;
    },
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("表格数据为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          this.copyTable.forEach((item) => {
            if (item.materialCode == selectedData[0].materialCode) {
              item.quantity = item.quantity - selectedData[0].quantity;
            }
          });
          //删除选中的数据
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    getOrderNum() {
      this.show = false;
      this.Fresh();
      this.ifShowOrderNum = true;
      this.OrderNumVisible = true;
    },
    confirmButton(show, sure) {
      this.show = show;
      this.sure = sure;
      if (this.sure == true) {
        this.Send();
        this.Fresh();
        this.sure = false;
      }
    },
    cancelButton(show, sure) {
      this.show = show;
      this.sure = sure;
    },
    //传回来把组件关闭
    Sure(val) {
      this.location = val;
      this.Res.StorehouseName = this.location;
      this.ShowStatue = false;
      // 获取提交数据的子项编号
      this.item = ""; //清空上一次数据
      this.stoDate.forEach((item) => {
        if (item.material == this.ShowData.materialCode) {
          this.item = item.item;
        }
      });
      this.getOther();
      this.$refs.code.focus();
    },
    //日期格式
    DateFormat(date) {
      let wholeDate = "20" + date;
      return `${wholeDate.substring(0, 4)}-${wholeDate.substring(
        4,
        6
      )}-${wholeDate.substring(6, 8)}`;
    },
    //主列表数据
    getOther() {
      let SCdata = this.DateFormat(this.Res.prodDate);
      let YXdata = this.DateFormat(this.Res.BBD);
      this.detailData.push({
        UniqueId: this.Res.palletNo,
        SupplierId: this.Res.commerialVendor,
        Num: this.Res.quantity,
        Unit: this.Res.uom,
        BatchNO: this.Res.batchCod,
        ProductionDate: SCdata,
        ExpDate: YXdata,
        ProducerId: this.Res.gsVendor,
        PONO: this.Res.poNo,
        BaoJanNo: this.Res.inspectionNumber,
        SupplyBatchNO: this.Res.vendorBatch,
        GuiGe: this.Res.materialCfg,
        ProductId: this.Res.materialCode,
        StorehouseName: this.Res.StorehouseName,
        WareHouseId: "0020",
        WareHouseName: "0020",
        InventoryStatus: "U",
        Item: this.item,
      });
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    //提交
    async Send() {
      let type = "PurchaseIn";
      let submit = {
        LinkNo: this.orderPur,
        BillType: "PurchaseIn",
        BillTypeName: "PO收货",
        InventoryStatus: "U",
        InDate: this.getNowDate(),
        CreatedId: JSON.parse(localStorage.getItem("userid")),
        CreatedName: JSON.parse(localStorage.getItem("username")),
        // Plant: this.orderNum,
        VisualCheck: this.ms,
        AdvanceSendSample: this.tqdy,
        COA: this.coa,
        InBulk: this.sz,
      };
      let res = await InformationSubmit(
        type,
        JSON.stringify(submit),
        JSON.stringify(this.detailData)
      );
      if (res.status == 200) {
        toast(res.msg);
        this.rowData = [];
        this.submitData = [];
        this.detailData = [];
      } else {
        toast(res.d.message);
      }
    },
    async onSubmit() {
      this.addPrice();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        let restwo = await PostOrder("/api/IMSPDA/getPurOrder", {
          sdate: this.startDate,
          edate: this.endDate,
          keys: this.keyword,
        });
        if (restwo.status == 200) {
          restwo.data.data.forEach((item) => {
            this.newArry.push(item.purNo);
          });
          if (this.newArry.indexOf(this.orderPur) == -1) {
            this.$toast("改订单已关闭,无法提交");
          } else {
            const res = await PostDetail("/api/IMSPDA/getPurItem", {
              OrderNO: this.orderPur,
            });
            if (res.status == 200) {
              this.newDetails = res.data.data;
              this.noFitWuliao = [];
              this.copyTable.forEach((item) => {
                this.newDetails.forEach((itemtwo) => {
                  if (item.materialCode == itemtwo.material) {
                    if (
                      Number(item.quantity) >
                      Number(itemtwo.quantity) - Number(itemtwo.aquantity)
                    ) {
                      this.noFitWuliao.push(itemtwo.materialName);
                    }
                  }
                });
              });
              if (this.noFitWuliao[0] == null) {
                this.$toast({
                  type: "success",
                  message: "提交成功",
                });
                this.Send();
                this.Fresh();
                this.newArry = [];
              } else {
                this.ifShowNoFit = true;
              }
            } else {
              this.$toast("后台发生错误,请联系管理员");
            }
          }
        } else {
          this.$toast("后台错误,无法提交");
        }
      }
    },
    addPrice() {
      let copymodel = [];
      let Model = [];
      for (var i in this.rowData) {
        copymodel.push(this.rowData[i].model);
      }
      for (var j in copymodel) {
        if (Model.indexOf(copymodel[j]) == -1) {
          Model.push(copymodel[j]);
        }
      }
      //得到了所有的model种类
      //console.log(Model);
      //将Model以属性的方式放入对象数组DX,
      //并且给对象数组DX添加price属性
      let DX = [];
      Model.map((item) => {
        DX.push({
          model: item,
        });
      });
      DX.forEach((itm) => {
        itm.price = 0;
      });
      //遍历rowdata中的所有model将所有的price累加赋值给DX.price
      for (var k in DX) {
        for (var m in this.rowData) {
          if (this.rowData[m].model == DX[k].model) {
            DX[k].price += parseInt(this.rowData[m].price);
          }
        }
      }
      this.DX = DX;
    },
    Fresh() {
      this.copyTable = [];
      this.$store.state.ph = "";
      this.$store.state.wl = "";
      this.$store.state.sl = "";
      this.orderPur = "";
      this.orderNum = "";
      this.code = "";
      this.rowData = [];
      this.otherData = [];
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.closeEnter();
  },
};
</script>

<style scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}

.van-field__label {
  margin-right: 0 !important;
}

.van-nav-bar__conten {
  height: 2.75rem !important;
}
.first {
  display: flex;
  justify-content: space-evenly;
}
.tip {
  text-align: center;
  margin-bottom: 1rem;
  padding: 1rem;
  height: 1rem;
}
</style>

